<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\common\Common;

use app\admin\model\Povertypolicy as PovertypolicyMdl;
use app\admin\model\Image;
use app\admin\model\Povertypolicyledger;
use app\admin\model\Member;
use app\admin\model\Memberextrainfo;
//use app\admin\model\Villages;
//use app\admin\model\Area;
use app\admin\service\Povertypolicy as PovertypolicyService;

use think\Db;
use think\Exception;
use think\Request;

class Povertypolicy extends Base
{

    public function _initialize() {
        parent::_initialize();

        $ledgerId = $this->request->param('ledgerId');
        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['policyledgerId'] = $ledgerId;
        $this->defaultWhere = $defaultWhere;

        $this->assign('ledgerId', $ledgerId);
    }

    public function index(){
        $request = $this->request;
        $policyledgerInfo = Povertypolicyledger::where(['id' => $request->param('ledgerId')])->find();

        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $order = 'createDate DESC';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($where, $this->defaultWhere);
            }

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as $item) {
                $memberInfo = Member::where(['id' => $item['memberId']])->field('name')->find();
                // 户主
                $householderName = Member::where(['id' => $item['householderId']])->value('name');
                $item['memberName'] = $memberInfo['name'] . ' (户主：' . $householderName . ')';

                $policyList = json_decode($item['policy'], true);
                $index = 0;
                /*foreach ($policyList as $policyKey => $policy) {
                    if(count($policy['policySpec']) > 1){
                        // 多列
                        foreach($policy['policySpec'] as $policySpec){
                            $item["explainValue_$index"] = $policySpec['explainValue'];
                            $index ++;
                        }
                    }else{
                        // 一列
                        $policySpec = $policy['policySpec'][0];
                        $item["explainValue_$index"] = $policySpec['explainValue'];
                        $index ++;
                    }
                }*/
                $policyledgerList = json_decode($policyledgerInfo['policy'], true);
                foreach ($policyledgerList as $policyKey => $policy) {
                    if(count($policy['policySpec']) > 1){
                        // 多列
                        foreach($policy['policySpec'] as $policySpecKey => $policySpec){
                            if (isset($policyList[$policyKey]['policySpec'][$policySpecKey])) {
                                $policySpec = $policyList[$policyKey]['policySpec'][$policySpecKey];
                                $item["explainValue_$index"] = $policySpec['explainValue'];
                            } else {
                                $item["explainValue_$index"] = '';
                            }

                            $index ++;
                        }
                    }else{
                        // 一列
                        if (isset($policyList[$policyKey]['policySpec'][0])) {
                            $policySpec = $policyList[$policyKey]['policySpec'][0];
                            $item["explainValue_$index"] = $policySpec['explainValue'];
                        } else {
                            $item["explainValue_$index"] = '';
                        }

                        $index ++;
                    }
                }
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        //$policyledgerInfo = Povertypolicyledger::where(['id' => $request->param('ledgerId')])->find();
        $policyList = json_decode($policyledgerInfo['policy'], true);
        // 自定义表头
        // 第一行
        $customHeader = '<tr>';
            $customHeader .= '<th rowspan="2" style="vertical-align: middle;">姓名</th>';
            foreach ($policyList as $policy1) {
                if(count($policy1['policySpec']) > 1){
                    // 多列
                    $customHeader .= '<th colspan="'.count($policy1['policySpec']).'">' . show_policys($policy1['policyType']) . '</th>';
                }else{
                    // 一列
                    if($policy1['policySpec'][0]['specType'] != 0){
                        $customHeader .= '<th colspan="1">' . show_policys($policy1['policyType']) . '</th>';
                    }else{
                        //$customHeader .= '<th rowspan="2" style="vertical-align: middle;">' . show_policys($policy1['policyType']) . '</th>';
                        $customHeader .= '<th colspan="1">' . show_policys($policy1['policyType']) . '</th>';
                    }
                }
            }
            $customHeader .= '<th rowspan="2" style="vertical-align: middle;">备注</th>';
            $customHeader .= '<th rowspan="2" style="vertical-align: middle;">操作</th>';
        $customHeader .= '</tr>';
        // 第二行
        $customHeader .= '<tr>';
            //$customHeader .= '<th>姓名</th>';
            foreach ($policyList as $policy2) {
                if(count($policy2['policySpec']) > 1){
                    // 多列
                    foreach($policy2['policySpec'] as $policySpec2){
                        switch($policySpec2['specType']){
                            case 1:
                                $customHeader .= '<th>' . show_quarter($policySpec2['quarter']) . '</th>';
                                break;
                            case 2:
                                $customHeader .= '<th>' . show_month($policySpec2['month']) . '</th>';
                                break;
                            default: break;
                        }
                    }
                }else{
                    // 一列
                    $policySpec2 = $policy2['policySpec'][0];
                    if($policySpec2['specType'] != 0){
                        switch($policySpec2['specType']){
                            case 1:
                                $customHeader .= '<th>' . show_quarter($policySpec2['quarter']) . '</th>';
                                break;
                            case 2:
                                $customHeader .= '<th>' . show_month($policySpec2['month']) . '</th>';
                                break;
                            default: break;
                        }
                    }else{
                        $customHeader .= '<th>无</th>';
                    }
                }
            }
            //$customHeader .= '<th>备注</th>';
            //$customHeader .= '<th>操作</th>';
        $customHeader .= '</tr>';

        // Table 内容
        $tableColumns = [];
        $tableColumns[] = ['data' => 'memberName'];
        $j = 0;
        foreach ($policyList as $policy3) {
            if(count($policy3['policySpec']) > 1){
                // 多列
                foreach($policy3['policySpec'] as $policySpec3){
                    $tableColumns[] = ['data' => "explainValue_$j"];
                    $j ++;
                }
            }else{
                // 一列
                $tableColumns[] = ['data' => "explainValue_$j"];
                $j ++;
            }
        }
        $tableColumns[] = ['data' => 'remark'];
        $tableColumns[] = [
            'data' => 'null',
            'defaultContent' => '<a href="javascript:;" type="button" class="btn btn-success edit-btn">编辑</a><button type="button" class="btn btn-danger delete-btn">删除</button>'
        ];

        $this->assign('area', $this->getArea($policyledgerInfo));
        $this->assign('povertypolicyledger', $policyledgerInfo);
        $this->assign('customHeader', $customHeader);
        $this->assign('tableColumns', json_encode($tableColumns));

        return parent::index();
    }

    public function add(Request $request) {
        $request = $this->request;
        $policyledgerInfo = Povertypolicyledger::where(['id' => $request->param('ledgerId')])->find();
        $policyList = json_decode($policyledgerInfo['policy'], true);

        $this->assign('area', $this->getArea($policyledgerInfo));
        $this->assign('povertypolicyledger', $policyledgerInfo);
        $this->assign('policyList', $policyList);

        return parent::add($request);
    }

    public function edit(Request $request) {
        $request = $this->request;
        $model = model($this->model);
        $id = $request->param('id');
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        if($info['householderId']){
            $info['householderName'] = Member::where('id', $info['householderId'])->value('name');
        }
        if($info['memberId']){
            $info['memberName'] = Member::where('id', $info['memberId'])->value('name');
        }

        $this->assign('area', $this->getArea($info));

        $policyledgerInfo = Povertypolicyledger::where(['id' => $request->param('ledgerId')])->find();
        //$policyList = json_decode($policyledgerInfo['policy'], true);
        $policyList = json_decode($info['policy'], true);

        $this->assign('povertypolicyledger', $policyledgerInfo);
        $this->assign('policyList', $policyList);

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    public function savePost(Request $request, $redirect = '') {
        $redirect = url('admin/povertypolicy/index', ['ledgerId' => $request->param('ledgerId')]);
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();

            // 贫困户是否已添加了政策享受
            if(!isset($data['oriMemberId']) || (isset($data['oriMemberId']) && $data['oriMemberId'] != $data['memberId'])){
                $where = [
                    'policyledgerId' => $data['policyledgerId'],
                    'memberId' => $data['memberId']
                ];
                $povertypolicyInfo = $model->where($where)->field('memberId')->find();
                if($povertypolicyInfo){
                    return $this->error('该村民已添加过此政策享受！');
                }
            }

            try {
                Db::startTrans();

                $policyType = (Array)$data['policyType'];
                $policy = [];
                foreach ($policyType as $key => $value) {
                    $specType = isset($data["specType_$key"]) ? (Array)$data["specType_$key"] : [];
                    $quarter = isset($data["quarter_$key"]) ? (Array)$data["quarter_$key"] : [];
                    $month = isset($data["month_$key"]) ? (Array)$data["month_$key"] : [];
                    $explain = isset($data["explain_$key"]) ? (Array)$data["explain_$key"] : [];
                    $explainValue = isset($data["explainValue_$key"]) ? (Array)$data["explainValue_$key"] : [];
                    // 享受政策规格
                    $policySpec = [];
                    foreach ($specType as $ke => $val) {
                        $policySpec[] = [
                            'specType' => $val,
                            'quarter' => isset($quarter[$ke]) ? $quarter[$ke] : '',
                            'month' => isset($month[$ke]) ? $month[$ke] : '',
                            'explain' => isset($explain[$ke]) ? $explain[$ke] : '',
                            'explainValue' => isset($explainValue[$ke]) ? $explainValue[$ke] : '',
                        ];
                    }

                    $policy[] = [
                        'policyType' => $value,
                        'policySpec' => $policySpec
                    ];
                }
                $data['policy'] = json_encode($policy);

                if(isset($data['id']) && $data['id']){
                    $data['updateDate'] = time();
                    $data['updateOper'] = $this->admin->id;

                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                    if($result !== false) {
                        // Query执行后的操作
                        $model->_after_update($data);

                        // 写入日志
                        $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                        Common::adminLog($request, $logInfo);

                        Db::commit();
                        return $this->success('保存成功！', $redirect);
                    } else {
                        Db::rollback();
                        return $this->error($model->getError());
                    }
                }

                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();
                $data['createOper'] = $this->admin->id;

                $result = $model->save($data);

                if($result !== false) {
                    // Query执行后的操作
                    $model->_after_insert($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('添加成功！', $redirect);
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误！');
        }
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if($id){
            // 删除一条
            $info = $model->find(['id', $id]);
            if(!$info){
                return $this->error('该政策享受不存在！');
            }
            //$result = $info->update(['status' => 90]);
            $result = $model->where('id', $id)->delete();

            if($result !== false){
                // Query执行后的操作
                $model->_after_delete($id);

                $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);
            }
        }

        if($result !== false){
            return $this->success('删除成功！');
        }else{
            return $this->error('删除失败！');
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }
        }

        return $where;
    }

    /**
     * 村民列表
     */
    public function memberList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Member');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $householderId = $param['householderId'];
        $memberIds = Memberextrainfo::where(['householderId' => $householderId])->field('memberId')->select();
        $memberIds = array_column($memberIds, 'memberId');
        // 家庭成员包括户主自己
        $memberIds[] = $householderId;
        $where = [
            'id' => ['in', $memberIds]
        ];
        $list = $model->where($where)->limit($start, $length)->select();
        $count = $model->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 下载Excel模板
     */
    public function downloadTemplate(){
        PovertypolicyService::downloadTemplate($this->request);
    }

    /**
     * 导入数据
     */
    public function import(){
        $result = PovertypolicyService::import();

        return $result;
    }

    /**
     * 导出数据
     */
    public function export(){
        $param = $this->request->param();
        $result = PovertypolicyService::export($this->request);
        if($result['code'] == 2){
            $this->error($result['msg']);
        }

        $redirect = url('admin/povertypolicy/index', ['ledgerId' => $param['ledgerId']]);
        return redirect($redirect);
    }

}
